import { ref } from "vue";
import { ElMessage } from "element-plus";
import {
  getConfigurationList,
  deleteConfiguration,
  createConfiguration,
  updateConfiguration,
} from "@/api/system-configuration";

export default () => {
  // 参数设置
  const columns4 = [
    {
      title: "编号",
      prop: "id",
    },
    {
      title: "关键字",
      prop: "code",
    },
    {
      title: "值",
      prop: "value",
    },
    {
      title: "描述",
      prop: "illustrate",
    },
    {
      title: "缓存类型",
      prop: "cacheType",
    },
    {
      title: "操作",
      formatter: true,
    },
  ];

  const defaultQuery = {
    page: 1,
    limit: 100,
    robotType: "patroling",
  };

  // 参数设置数据
  const list4 = ref([]);
  async function getConfig() {
    const { data } = await getConfigurationList(defaultQuery);
    list4.value = data ? data.list : [];
  }
  getConfig();

  /**
   * @description: 删除参数
   * @param {*} id
   * @return {*}
   */
  async function delConfig(id) {
    await deleteConfiguration(id);
    ElMessage.success({
      message: "删除成功",
    });
    getConfig();
  }

  // 参数设置表单
  const configFormOptions = ref([
    {
      prop: "code",
      label: "关键字",
    },
    {
      prop: "value",
      label: "值",
    },
    {
      prop: "illustrate",
      label: "描述",
    },
    {
      prop: "cacheType",
      label: "缓存类型",
    },
  ]);

  // add：新增，edit：修改
  const currentAction = ref("");
  const configSettingVisible = ref(false);
  const configFormData = ref({});
  /**
   * @description: 打开参数设置弹窗
   * @param {*} type add：新增，edit：修改
   * @return {*}
   */
  async function openConfigSetting(type, row = { id: "" }) {
    currentAction.value = type;
    configSettingVisible.value = true;
    if (currentAction.value === "edit") {
      const {
        data: { list = [] },
      } = await getConfigurationList({ ...defaultQuery, id: row.id });
      if (list && list.length >= 0) {
        configFormData.value = list[0];
      }
    }
  }

  /**
   * @description: 处理参数配置
   * @return {*}
   */
  async function handleConfig(formData) {
    const data = { ...formData };
    data.robotType = "patroling";
    if (currentAction.value === "add") {
      await createConfiguration(data);
      ElMessage.success({
        message: "提交成功",
      });
    } else if (currentAction.value === "edit") {
      await updateConfiguration(data);
      ElMessage.success({
        message: "修改成功",
      });
    }
    configSettingVisible.value = false;
    getConfig();
  }

  return {
    columns4,
    list4,
    configFormOptions,
    configSettingVisible,
    openConfigSetting,
    handleConfig,
    delConfig,
    configFormData,
  };
};
